package oop.ex1.filters;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeSet;

//###############
//FILE : DateFilter.java
//WRITER : Amir Wilf, wilfoa, 300007085
//WRITER : Daniel Acherkan, danithelion, 310116348
//EXERCISE : oop ex1 2011
//DESCRIPTION:
//A file filter which filter files by their last modified date
//###############

/**
 * A file filter which filter files their last modified date
 */
public class DateFilter extends OrderFilter {
	//the date format to be used with this filter
	protected final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
			"yyyy/MM/dd");

	// Constants:
	// DELTA - the number of miliseconds on 23:59:59 hours. Needed so the
	// filter wouldn't present files modified in the same day as in the
	// commandFile.
	protected final long DELTA = 86399000;

	// Data Memebers:
	protected Date _date;

	// Constructor
	public DateFilter(boolean direction, boolean not, String parameter) {
		super(direction, not);
		// parse the parameter to compare by
		parseParameter(parameter);
	}

	/**
	 * filters the files according to their last date of modification.
	 * @param fullDirectoryFiles A TreeSet of all the files in question, 
	 * before filtering.
	 * @return A TreeSet of the files modified before/after a given date.
	 */
	@Override
	public TreeSet<File> filter(TreeSet<File> fullDirectoryFiles) {
		TreeSet<File> list = new TreeSet<File>();
		for (File file : fullDirectoryFiles) {
			// case this filter is an After filter:
			if (this._direction) {
				//comparing each file with the filter's date:
				if (new Date(file.lastModified()).getTime() > this._date
						.getTime() + DELTA) {
					list.add(file);
				}
				
			//case this filter is a Before filter:
			} else {
				//comparing each file with the filter's date:
				if (new Date(file.lastModified()).getTime() < this._date
						.getTime() + DELTA) {
					list.add(file);
				}
			}
		}
		//taking the negation possibility into consideration:
		return addNegation(list, fullDirectoryFiles);
	}

	//This method parses the the date into a Date object
	protected void parseParameter(String size) {
		try {
			_date = DATE_FORMAT.parse(size);
		} catch (ParseException e) {
			throw new IllegalArgumentException();
		}
	}

}
